package com.xyh.concurrency.example.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import lombok.extern.slf4j.Slf4j;

/**
 * juc 中的锁
 */
@Slf4j
public class LockExample5 {


    public static void main(String[] args) {
        //创建锁对象
        ReentrantLock reentrantLock = new ReentrantLock();
        //获取 Condition  对象所以当前对象都是当前锁中的信息
        Condition condition = reentrantLock.newCondition();
        new Thread(() -> {
            try {
                //线程 1 上锁
                reentrantLock.lock();
                log.info("kaish");//1
                //使线程1等待信号
                condition.await();
            } catch (Exception e) {
                e.printStackTrace();
            }
            log.info("get signal");//4
            reentrantLock.unlock();
        }).start();
        new Thread(() -> {
            //线程2上锁
            reentrantLock.lock();
            log.info("get lock");//2
            try {
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //唤醒等待的线程 将线程从等待的线程获取出来
            condition.signalAll();
            log.info("send signal_11");//3
            //释放线程二
            reentrantLock.unlock();
        }).start();
    }

}
